package com.renwei.yunlong.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.activity.work.SendWorkActivity;
import com.renwei.yunlong.adapter.TablayoutAdapter;
import com.renwei.yunlong.base.BaseFragment;
import com.renwei.yunlong.bean.LoginBean;
import com.renwei.yunlong.bean.ServiceLoginBean;
import com.renwei.yunlong.bean.SwitchCompanyBean;
import com.renwei.yunlong.bean.UpcomingBean;
import com.renwei.yunlong.event.MainRefreshEvent;
import com.renwei.yunlong.event.WorkNumberEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.SharedPreUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * Created by wangqi on 2017/9/28.
 */

public class WorkFragment extends BaseFragment implements View.OnClickListener, HttpTaskListener {
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.vp_work)
    ViewPager vpWork;
    @Bind(R.id.tab_indicator)
    XTabLayout tabLayout;
    @Bind(R.id.iv_daiban)
    ImageView ivDaiban;
    @Bind(R.id.tv_bar_daiban)
    TextView tvBarDaiban;
    @Bind(R.id.iv_jingban)
    ImageView ivJingban;
    @Bind(R.id.tv_bar_jingban)
    TextView tvBarJingban;
    @Bind(R.id.rl_daiban)
    RelativeLayout rlDaiban;
    @Bind(R.id.rl_jingban)
    RelativeLayout rlJingban;
    @Bind(R.id.hint_view)
    View hintView;
    @Bind(R.id.iv_all)
    ImageView ivAll;
    @Bind(R.id.tv_bar_all)
    TextView tvBarAll;
    @Bind(R.id.rl_all)
    RelativeLayout rlAll;
    private List<Fragment> mFragments;
    private PopupWindow popupWindow;
    private String[] titles;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_work;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initPopup();
        initFragment();
        simpleTileView.setLeftImageViewVisibility(View.INVISIBLE);
        simpleTileView.setLeftClickListener(null);
        if ("1".equals(companyType)) {
            simpleTileView.setTitle(ownerBean.getRows().getCompany().getCompanyName());
        } else if ("2".equals(companyType)) {
            simpleTileView.setTitle(serviceLoginBean.getRows().getCompany().getCompanyName());
        }
        Drawable titleLeft = getContext().getResources().getDrawable(R.mipmap.tri);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        simpleTileView.getTitleView().setCompoundDrawables(null, null, titleLeft, null);
        simpleTileView.getTitleView().setCompoundDrawablePadding(10);
        simpleTileView.getTitleView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 切换公司
                getOtherCompany();
            }
        });
        simpleTileView.setRightOption(R.mipmap.plus, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 发起工单
                Intent intent = new Intent(getActivity(), SendWorkActivity.class);
                startActivity(intent);
            }
        });

        if ("1".equals(companyType)) {
            if (AppHelper.isAdminDesk(ownerBean)) {
                rlAll.setVisibility(View.VISIBLE);
            } else {
                rlAll.setVisibility(View.GONE);
            }
        } else {
            if (AppHelper.isAdminDesk(serviceLoginBean)) {
                rlAll.setVisibility(View.VISIBLE);
            } else {
                rlAll.setVisibility(View.GONE);
            }
        }

        tvBarJingban.setVisibility(View.GONE);
        tvBarAll.setVisibility(View.GONE);
        rlAll.setOnClickListener(this);
        rlDaiban.setOnClickListener(this);
        rlJingban.setOnClickListener(this);
        TablayoutAdapter adapter = new TablayoutAdapter(getChildFragmentManager(), mFragments, titles);
        vpWork.setAdapter(adapter);
        vpWork.setOffscreenPageLimit(4);
        tabLayout.setupWithViewPager(vpWork);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
    }

    @Override
    public void onResume() {
        super.onResume();
        getWorkNumber();
    }

    private void getWorkNumber() {
        HashMap<String, String> map = new HashMap<>();
        map.put("kind", "0");
        map.put("startDate", "");
        map.put("endDate", "");
        map.put("contractId", "");
        map.put("content", "");
        map.put("page", "1");
        map.put("rows", 20 + "");
        if ("2".equals(companyType)) {
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("ownerCode", "");
        } else if ("1".equals(companyType)) {
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", "");
        }
        ServiceRequestManager.getManager().getWorkList(getContext(), "1",
                JsonMapUtil.mapToJson(map), this);
    }

    private void initFragment() {
        titles = new String[]{"解决率", "SLA", "满意度", "投诉率"};
        mFragments = new ArrayList<>();
        mFragments.add(new WorkResolutionFragment());
        mFragments.add(new WorkSLAFragment());
        mFragments.add(new WorkSatisfiedFragment());
        mFragments.add(new WorkComplaintFragment());
    }

    private void initPopup() {
        if (popupWindow == null) {
            View view = getActivity().getLayoutInflater().inflate(R.layout.pop_swich_title, null);
            popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setFocusable(true);
            popupWindow.setAnimationStyle(R.style.pop_animation_top);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(0000000000));
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    Drawable titleLeft = getContext().getResources().getDrawable(R.mipmap.tri);
                    titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
                    simpleTileView.getTitleView().setCompoundDrawables(null, null, titleLeft, null);
                    simpleTileView.getTitleView().setCompoundDrawablePadding(10);
                    hintView.setVisibility(View.GONE);
                }
            });
        }
    }

    private void getOtherCompany() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().getOtherCompany(getContext(), JsonMapUtil.mapToJson(map), this);
    }

    private void showTitlePop(List<SwitchCompanyBean.RowsBean> rows) {
        if (rows == null || rows.size() == 0) {
            rows = new ArrayList<>();
        }
        SwitchCompanyBean.RowsBean rowBean = new SwitchCompanyBean.RowsBean();
        rowBean.setCompanyName(simpleTileView.getTitle().toString().trim());
        rows.add(0, rowBean);

        View view = popupWindow.getContentView();
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        final PopupAdapter adapter = new PopupAdapter(getContext());
        adapter.setData(rows);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                SwitchCompanyBean.RowsBean bean = adapter.getData().get(position);
                if (!bean.getCompanyName().equals(simpleTileView.getTitle().toString())) {
                    updateCompany(bean);
                } else {
                    popupWindow.dismiss();
                }
            }
        });
        popupWindow.showAsDropDown(simpleTileView);
//        popupWindow.showAtLocation(tabLayout, Gravity.BOTTOM,0,0);
        hintView.setVisibility(View.VISIBLE);
        Drawable titleLeft = getContext().getResources().getDrawable(R.mipmap.up);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        simpleTileView.getTitleView().setCompoundDrawables(null, null, titleLeft, null);
        simpleTileView.getTitleView().setCompoundDrawablePadding(10);
    }

    private void updateCompany(SwitchCompanyBean.RowsBean bean) {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("userName", ownerBean.getRows().getUserName());
            String ownerPwd = SharedPreUtil.getString(getActivity(), "owner_pwd", "");
            map.put("password", ownerPwd);
        } else if ("2".equals(companyType)) {
            map.put("userName", serviceLoginBean.getRows().getUserName());
            String servPwd = SharedPreUtil.getString(getActivity(), "service_pwd", "");
            map.put("password", servPwd);
        }
        map.put("companyCode", bean.getCompanyCode());
        map.put("phoneFlag", "0");
        map.put("deviceToken", YunLongApplication.getDeviceToken());
        ServiceRequestManager.getManager().updateCompany(getContext(), JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.rl_all:
//                MyDealWorkActivity.OpenActivity(getContext(), "0");
//                break;
//            case R.id.rl_daiban:
//                MyDealWorkActivity.OpenActivity(getContext(), "1");
//                break;
//            case R.id.rl_jingban:
//                MyDealWorkActivity.OpenActivity(getContext(), "2");
//                break;
//                default:
//                break;
//        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                SwitchCompanyBean bean = new Gson().fromJson(result, SwitchCompanyBean.class);
                showTitlePop(bean.getRows());
                break;
            case 2:
                if ("1".equals(companyType)) {
                    LoginBean value = new Gson().fromJson(result, LoginBean.class);
                    if (value.getMessage().getCode() == 200) {

                        // 友盟 推送接口
                        HashMap<String, String> map = new HashMap<>();
                        map.put("deviceToken", YunLongApplication.getDeviceToken());
                        map.put("phoneFlag", "0");
                        map.put("userId", value.getRows().getEmployeeId());
                        map.put("ownerCode", value.getRows().getOwnerCode());
                        ServiceRequestManager.getManager().pushInit(getContext(), JsonMapUtil.mapToJson(map), null);

                        mCache.put("loginBean", value);
                        mCache.put("companyType", "1");
                        EventBus.getDefault().post(new MainRefreshEvent());
                    } else {
                        showCenterInfoMsg(value.getMessage().getMessage());
                    }
                } else if ("2".equals(companyType)) {
                    ServiceLoginBean value = new Gson().fromJson(result, ServiceLoginBean.class);
                    if (value.getMessage().getCode() == 200) {

                        // 友盟 推送接口
                        HashMap<String, String> map = new HashMap<>();
                        map.put("deviceToken", YunLongApplication.getDeviceToken());
                        map.put("phoneFlag", "0");
                        map.put("userId", value.getRows().getEmployeeId());
                        map.put("serviceProviderCode", value.getRows().getServiceProviderCode());
                        ServiceRequestManager.getManager().pushInit(getContext(), JsonMapUtil.mapToJson(map), null);

                        mCache.put("serviceLoginBean", value);
                        mCache.put("companyType", "2");
                        EventBus.getDefault().post(new MainRefreshEvent());
                    } else {
                        showCenterInfoMsg(value.getMessage().getMessage());
                    }
                }
                popupWindow.dismiss();
                break;
            case 3: // 获取work待办数
                UpcomingBean upcomingBean = new Gson().fromJson(result, UpcomingBean.class);
                if (upcomingBean.getMessage().getCode() == 200) {
                    EventBus.getDefault().post(new WorkNumberEvent(upcomingBean.getTotal()));
                    CommonUtils.setBarTextView(tvBarDaiban, upcomingBean.getTotal());
                }
                break;
                default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
    }

    // 选择企业  adapter
    class PopupAdapter extends BaseRecyclerViewAdapter<SwitchCompanyBean.RowsBean> {

        public PopupAdapter(Context context) {
            super(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new PopViewHolder(inflater.inflate(R.layout.item_company_title, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            SwitchCompanyBean.RowsBean item = getItem(position);
            PopViewHolder popViewHolder = (PopViewHolder) holder;
            if (item != null) {
                String title = simpleTileView.getTitle().toString();
                if (title.equals(item.getCompanyName())) {
                    popViewHolder.tvTitle.setTextColor(Color.parseColor("#689DF8"));
                    popViewHolder.ivCheck.setVisibility(View.VISIBLE);
                } else {
                    popViewHolder.tvTitle.setTextColor(Color.parseColor("#333333"));
                    popViewHolder.ivCheck.setVisibility(View.GONE);
                }
                popViewHolder.tvTitle.setText(item.getCompanyName());
            }
            popViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickLitener.onItemClick(v, position);
                }
            });
        }

        class PopViewHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.tv_title)
            TextView tvTitle;
            @Bind(R.id.iv_check)
            ImageView ivCheck;

            public PopViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
